﻿using System;
using System.Text;
using UnityEngine;
using BestHTTP.WebSocket;
using LitJson;
using Newtonsoft.Json;
using HsVoice;
namespace HuoSan
{
    public class AsrClient : MonoBehaviour
    {
        private WebSocket wws;
        private void Start()
        {
            wws = new WebSocket(new Uri("wss://openspeech.bytedance.com/api/v2/asr"));
            wws.InternalRequest.SetHeader("Authorization","VVGpAR6xVinDHcepQeVsdc1LzTQfF8Eq");
            wws.OnOpen += OnOpen;
            wws.OnMessage += om;
            wws.OnBinary += OnBinary;
            wws.OnError += OnError;
            wws.Open();
        }

        private void OnError(WebSocket websocket, Exception ex)
        {
           Debug.Log(ex.Message);
        }

        private void OnBinary(WebSocket websocket, byte[] data)
        {
            Debug.Log(data.Length);
        }

        private void om(WebSocket websocket, string message)
        {
            var bs = Encoding.UTF8.GetBytes(message);
            Array.Reverse(bs);
            var r = bs.ToGUnzip();
            Debug.Log(r.Length);
        }

        private void OnOpen(WebSocket websocket)
        {
            AsrParams asrParams = new AsrParams();
            App app = new App();
            User user = new User();
            Request request = new Request();
            
            asrParams.app = app;
            asrParams.user = user;
            asrParams.request = request;

            int header_len = 4;
            byte[] header = new byte[header_len];
            header[0] = (byte) (0b0001 << 4 | (header_len >> 2));
            header[1] = (byte) (0b0001 << 4 | 0b0000);
            header[2] = (byte) (0b0001 << 4 | 0b0001);
            header[3] = 0;

            string arsJson = JsonMapper.ToJson(asrParams);
            byte[] payload = Encoding.UTF8.GetBytes(arsJson).ToGzip();
            int payload_len = payload.Length;
            byte[] pl_byte = BitConverter.GetBytes(payload_len);

            var sendBytes = header.MergeBytes(pl_byte).MergeBytes(payload);
            
            wws.Send(sendBytes);
        }
        
        
    }
}